package com.freak.wanandroid.model.navigation;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.freak.wanandroid.R;
import com.freak.wanandroid.base.fragment.BaseLifecycleFragment;
import com.freak.wanandroid.bean.NavigationBean;
import com.freak.wanandroid.model.navigation.activity.NavigationActivity;
import com.freak.wanandroid.model.navigation.adapter.NavigationLeftAdapter;
import com.freak.wanandroid.model.navigation.adapter.NavigationRightAdapter;

import java.util.List;

/**
 * 导航
 */
public class NavigationFragment extends BaseLifecycleFragment<NavigationViewModel> implements NavigationLeftAdapter.onItemSelectedListener {
    private RecyclerView mRecycleNavigationLeft;

    private RecyclerView mRecycleNavigationRight;

    private NavigationLeftAdapter mLeftAdapter;

    private NavigationRightAdapter mRightAdapter;

    private TextView mHeaderView;

    private NavigationBean mHeadMenu;

    private LinearLayout mHeaderLayout;//右侧菜单栏最上面的菜单

    private boolean mLeftClickType = false;//左侧菜单点击引发的右侧联动

    private List<NavigationBean> mDishMenuList;


    //    /**
//     * 断网重连
//     *
//     * @param networkType
//     */
//    @Override
//    public void onNetConnected(NetworkType networkType) {
//        super.onNetConnected(networkType);
//        mPresenter.getNavigation();
//    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_navigation;
    }

    @Override
    protected void initEventAndData(View view) {
        mRecycleNavigationLeft = view.findViewById(R.id.recycle_navigation_left);
        mRecycleNavigationLeft.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleNavigationRight = view.findViewById(R.id.recycle_navigation_right);
        mHeaderView = view.findViewById(R.id.right_menu_tv);
        mHeaderLayout = view.findViewById(R.id.right_menu_item);
//        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
//        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                return 0;
//            }
//        });
        mRecycleNavigationRight.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleNavigationRight.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {//无法下滑
                    showHeadView();
                    return;
                }
                View underView = null;
                if (dy > 0)
                    underView = mRecycleNavigationRight.findChildViewUnder(mHeaderLayout.getX(), mHeaderLayout.getMeasuredHeight() + 1);
                else
                    underView = mRecycleNavigationRight.findChildViewUnder(mHeaderLayout.getX(), 0);
                if (underView != null && underView.getContentDescription() != null) {
                    int position = Integer.parseInt(underView.getContentDescription().toString());
                    NavigationBean menu = mRightAdapter.getMenuOfMenuByPosition(position);
                    if (mLeftClickType || !menu.getName().equals(mHeadMenu.getName())) {
                        if (dy > 0 && mHeaderLayout.getTranslationY() <= 1 && mHeaderLayout.getTranslationY() >= -1 * mHeaderLayout.getMeasuredHeight() * 4 / 5 && !mLeftClickType) {// underView.getTop()>9
                            int dealtY = underView.getTop() - mHeaderLayout.getMeasuredHeight();
                            mHeaderLayout.setTranslationY(dealtY);
//                            Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+"   "+headerLayout.getBottom()+"  -  "+headerLayout.getMeasuredHeight() );
                        } else if (dy < 0 && mHeaderLayout.getTranslationY() <= 0 && !mLeftClickType) {
                            mHeaderView.setText(menu.getName());
                            int dealtY = underView.getBottom() - mHeaderLayout.getMeasuredHeight();
                            mHeaderLayout.setTranslationY(dealtY);
//                            Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+"   "+headerLayout.getBottom()+"  -  "+headerLayout.getMeasuredHeight() );
                        } else {
                            mHeaderLayout.setTranslationY(0);
                            mHeadMenu = menu;
                            mHeaderView.setText(mHeadMenu.getName());
                            for (int i = 0; i < mDishMenuList.size(); i++) {
                                if (mDishMenuList.get(i) == mHeadMenu) {
                                    mLeftAdapter.setSelectedNum(i);
                                    break;
                                }
                            }
                            if (mLeftClickType) mLeftClickType = false;
                            Log.e("TAG", "onScrolled: " + menu.getName());
                        }
                    }
                }
            }
        });
    }

    private void showHeadView() {
        mHeaderLayout.setTranslationY(0);
        View underView = mRecycleNavigationRight.findChildViewUnder(mHeaderView.getX(), 0);
        if (underView != null && underView.getContentDescription() != null) {
            int position = Integer.parseInt(underView.getContentDescription().toString());
            NavigationBean menu = mRightAdapter.getMenuOfMenuByPosition(position + 1);
            mHeadMenu = menu;
            mHeaderView.setText(mHeadMenu.getName());
            for (int i = 0; i < mDishMenuList.size(); i++) {
                if (mDishMenuList.get(i) == mHeadMenu) {
                    mLeftAdapter.setSelectedNum(i);
                    break;
                }
            }
        }
    }

    @Override
    protected void onResumeLoadData() {
        mViewModel.getNavigation();
        showLoading();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLeftAdapter.removeItemSelectedListener(this);
    }

    public void getNavigationSuccess(List<NavigationBean> navigationBeanList) {
        dismissLoading();
        mDishMenuList = navigationBeanList;
//        if (navigationBeanList != null && navigationBeanList.size() != 0) {
//            for (int i = 0; i < navigationBeanList.size(); i++) {
//                articlesList.addAll(navigationBeanList.get(i).getArticles());
//            }
        if (mLeftAdapter == null) {
            mLeftAdapter = new NavigationLeftAdapter(getActivity(), navigationBeanList);
            mRecycleNavigationLeft.setAdapter(mLeftAdapter);
        } else {
            mLeftAdapter.setData(navigationBeanList);
            mLeftAdapter.notifyDataSetChanged();
        }
//                ll_navigation_no_data.setVisibility(View.GONE);
//                recycle_navigation_right.setVisibility(View.VISIBLE);
        if (mRightAdapter == null) {
            mRightAdapter = new NavigationRightAdapter(getActivity(), navigationBeanList);
            mRecycleNavigationRight.setAdapter(mRightAdapter);
            mRightAdapter.setSelectInterface(articles -> {
                Intent intent = new Intent(getActivity(), NavigationActivity.class);
                intent.putExtra("url", articles.getLink());
                intent.putExtra("title", articles.getTitle());
                startActivity(intent);
            });
        } else {
            mRightAdapter.setData(navigationBeanList);
            mRightAdapter.notifyDataSetChanged();
        }
        mLeftAdapter.addItemSelectedListener(this);
        initHeadView();
        dismissLoading();
    }

    private void initHeadView() {
        mHeadMenu = mRightAdapter.getMenuOfMenuByPosition(0);
        mHeaderLayout.setContentDescription("0");
        mHeaderView.setText(mHeadMenu.getName());
    }

    /**
     * 左边菜单RecycleView接口
     *
     * @param postion
     * @param menu
     */
    @Override
    public void onLeftItemSelected(int postion, NavigationBean menu) {
        int sum = 0;
        for (int i = 0; i < postion; i++) {
            sum += mDishMenuList.get(i).getArticles().size() + 1;
        }
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecycleNavigationRight.getLayoutManager();
        layoutManager.scrollToPositionWithOffset(sum, 0);
        mLeftClickType = true;
    }

    @Override
    protected void dataObserver() {
        mViewModel.mGetNavigation.observe(this, this::getNavigationSuccess);
        mViewModel.mGetNavigationError.observe(this, s -> {
            dismissLoading();
        });
    }
}
